package feedback

import (
	"context"
	"fmt"
	"strings"

	"mall/service/backend/common/utils/pointy"
	"mall/service/recommended/rpc/internal/svc"
	"mall/service/recommended/rpc/types/recommended"

	"github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetFeedbackListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetFeedbackListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetFeedbackListLogic {
	return &GetFeedbackListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetFeedbackListLogic) GetFeedbackList(in *recommended.FeedbackListReq) (*recommended.FeedbackList, error) {
	if in.UserId == nil || len(strings.TrimSpace(*in.UserId)) == 0 {

	}
	logrus.Info(fmt.Sprintf("GetFeedbackList UserID: %+v", *in.UserId))
	var feedBackMap = make(map[string]*recommended.FeedbackInfo)
	if len(in.FeedbackType) > 0 {
		for _, v := range in.FeedbackType {
			res, err := l.svcCtx.GorseClient.GetUserFeedbacksWithType(l.ctx, *in.UserId, v)
			if err != nil {
				return nil, err
			}
			if len(res) > 0 {
				for _, f := range res {
					if _, ok := feedBackMap[f.ItemId]; !ok {
						feedBackMap[f.ItemId] = &recommended.FeedbackInfo{
							FeedbackType: pointy.GetPointer(f.FeedbackType),
							UserId:       pointy.GetPointer(f.UserId),
							ItemId:       pointy.GetPointer(f.ItemId),
							Timestamp:    pointy.GetPointer(f.Timestamp),
						}
					}
				}
			}
		}
	}

	var resp = &recommended.FeedbackList{}
	if len(feedBackMap) > 0 {
		for _, v := range feedBackMap {
			resp.List = append(resp.List, v)
		}
	}
	return resp, nil
}
